<template>
  <div>
    <el-form ref="attrForm" :rules="rules" :model="attr" label-width="70px">
      <el-form-item label="属性名" prop="attrName">
        <el-input v-model="attr.attrName" style="width: 400px" />
      </el-form-item>

    </el-form>

    <el-button :disabled="!attr.attrName" type="primary" icon="el-icon-plus" @click="addAttrValue">添加属性值</el-button>
    <el-table
      border
      style="width: 100%; margin:20px 0"
      :data="attr.attrValueList"
    >
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column
        label="属性值名称"
      >
        <template v-slot="{row, $index}">
          <el-input :ref="$index" v-model="row.valueName" placeholder="请输入属性名称" size="mini" @blur="isDelCurrentInout(row,$index)" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
      >
        <template v-slot="{$index}">
          <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="您真的要删除此项属性值吗？" @onConfirm="deleteCurrentAttrValue($index)">
            <el-tooltip slot="reference" content="删除属性值" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini" />
            </el-tooltip>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-button type="primary" @click="submitForm">确定</el-button>
    <el-button @click="$emit('setIsShowAttrList', true)">取消</el-button>
  </div>
</template>

<script>
import { reqSaveAttrInfo } from '@/api/product/attr'
import { mapState } from 'vuex'
export default {
  name: 'SaveAttr',
  props: {
    attrValue: {
      type: Object,
      // 添加一个默认值，为了实现一个正常的添加功能
      default: () => ({
        attrName: '',
        attrValueList: []
      })
    }
  },
  data() {
    // 自定义校验属性值名称
    // var validateAttrList = (rule, value, callback) => {
    //   if (!value.length) {
    //     callback(new Error('数组中不能为空，请至少添加一项属性值'))
    //     return
    //   }
    //   callback()
    // }
    return {
      attr: this.attrValue,
      rules: {
        attrName: [{ required: true, message: '请输入属性名称', trigger: 'blur' }]
        // attrValueList: [{ required: true, validator: validateAttrList }]
      }
    }
  },
  computed: {
    ...mapState('category', ['category3Id'])
  },
  methods: {
    // 1.添加属性值
    addAttrValue() {
      this.attr.attrValueList.push({
        valueName: ''
      })
      this.$nextTick(() => {
        this.$refs[this.attr.attrValueList.length - 1].focus()
      })
    },
    // 2.单击确定按钮时的校验
    submitForm() {
      this.$refs.attrForm.validate(async(valid) => {
        if (valid) {
          if (!this.attr.attrValueList.length) {
            this.$message({
              type: 'error',
              message: '请至少添加一个属性值'
            })
            return
          }
          // 发送请求存储sku属性
          const { attrName, attrValueList, id } = this.attr
          const { category3Id } = this
          const res = await reqSaveAttrInfo({ attrName, attrValueList, categoryId: category3Id, categoryLevel: 3, id })
          if (res.code === 200) {
            // 提示添加成功
            this.$message.success(`${id ? '修改' : '添加'}属性成功！`)
            // 跳转到之前页面
            this.$emit('setIsShowAttrList', true)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 3.如果没有添加属性值，则要删除当前项
    isDelCurrentInout(row, index) {
      if (!row.valueName) {
        // this.attr.attrValueList.splice(index, 1)
        this.attr.attrValueList.pop() // 删除数组最后一项
      }
    },
    // 4.删除某一项属性
    deleteCurrentAttrValue(index) {
      this.attr.attrValueList.splice(index, 1)
    }
  }
}
</script>

<style>

</style>
